package net.gazhi.delonix.grac.web.controller;

import java.util.List;

import net.gazhi.delonix.core.dao.PageInfo;
import net.gazhi.delonix.core.service.ValidationFaildException;
import net.gazhi.delonix.core.web.AbstractAnnotationController;
import net.gazhi.delonix.grac.entity.gru.Role;
import net.gazhi.delonix.grac.entity.gru.User;
import net.gazhi.delonix.grac.entity.gru.UserDir;
import net.gazhi.delonix.grac.form.UserSearchForm;
import net.gazhi.delonix.grac.service.RoleService;
import net.gazhi.delonix.grac.service.UserDirService;
import net.gazhi.delonix.grac.service.UserService;
import net.gazhi.delonix.grac.web.annonation.Handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/grac/user")
@Handler(zh = "用户管理", en = "Users")
public class UserController extends AbstractAnnotationController {

	@Autowired
	private UserDirService userDirService;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Handler(zh = "用户列表", en = "User List", redirectable = true)
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(UserSearchForm form) {
		PageInfo pageInfo = new PageInfo(form.getPageNo());
		List<UserDir> dirs = this.userDirService.listAll();
		if (form.getDirId() == null) {
			form.setDirId(dirs.get(0).getId());
		}
		List<User> users = this.userService.search(form, pageInfo);
		return new ModelAndView().addObject("dirs", dirs).addObject("users", users).addObject("pageInfo", pageInfo).addObject("form", form);
	}

	@Handler(zh = "用户编辑页面", en = "User Edit Page", redirectable = true)
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView edit(Long userId, Long dirId) {
		User user = null;
		UserDir dir = null;
		if (userId != null) {
			if (userId == 1L) {
				throw new ValidationFaildException("Can NOT Modify Super-Administrator!");
			}
			user = this.userService.get(userId);
			if (user == null) {
				throw new ValidationFaildException("User NOT Found: id=" + userId);
			}
			dir = user.getUserDir();
		} else {
			if (dirId == null) {
				throw new ValidationFaildException("UserId or DirId is REQUIRED!");
			}
			dir = this.userDirService.get(dirId);
			if (dir == null) {
				throw new ValidationFaildException("UserDir NOT Found: id=" + dirId);
			}
		}
		List<Role> roles = this.roleService.listAll();
		return new ModelAndView().addObject("user", user).addObject("dir", dir).addObject("roles", roles);
	}

}
